from wsgiref.simple_server import make_server, demo_app

def index(write):
    write("""<script>
function submit(e){
 if(!e)e=window.event;
 if(e.keyCode==13){
  url="/main/"+input.value;
  location.href=url
 }
}
</script>
<body>
<table width=100% height=60%>
<td width=100% height=100%><center><input id=input style="width:50%" value="enter your name" onkeypress="submit(event)">""")

def main(write,user):
    write('''<script>
function submit(e){
 if(!e)e=window.event;
 if(e.keyCode==13){
  url="/ajax/'''+str(user)+'''?"+input.value;
  input.value="";
  if(window.ActiveXObject){ajax=new ActiveXObject("Microsoft.XMLHTTP")};
  if(window.XMLHttpRequest){ajax=new XMLHttpRequest()};
  ajax.open("GET",url,true);
  ajax.send(null);
  //invis.src=url
 }
}
</script>
<body topmargin=0 bottommargin=0 leftmargin=0 rightmargin=0>
<table width=100% height=100% cellspacing=0 cellpadding=0>
<td width=80% height=100%>
<iframe id=thebox style="border-right:0;border-left:0;border-top:0;border-bottom:0" width=100% height=100% src="/top/'''+str(user)+'''"></iframe>
<td width=20% height=100%>
<iframe name=thelist style="border-right:0;border-left:0;border-top:0;border-bottom:0" width=100% height=100% src="/list/'''+str(user)+'''"></iframe>
<tr><td><input id=input style="width:100%" value="Type your message here" onkeypress="submit(event)">''')
    
import threading, Queue
class User():
    def __init__(self,name):
        self.q=Queue.Queue()
        self.name=name
    def __str__(self):
        return self.name
    def __repr__(self):
        return "User object: " + str(self)

   
class Server(threading.Thread):
    def __init__(self,httpd):
        self.httpd=httpd
        threading.Thread.__init__(self)
        self.setDaemon(1)
    def run(self):
        while 1:
            self.httpd.handle_request()

import socket

ulist=[]
def top(write,usern):
    u=User(usern) #create a new user object
    print "new user: "+str(u)
    ulist.append(u) #add it to the list of online users
    s=Server(httpd) #create a new thread to serve new requests
    s.start()
    refreshonlinelist() #tell all of the connected browsers to refresh their page
    write(" ")
    while 1:
        try:
            write(u.q.get()) #wait for new message to be sent to browser
        except socket.error:
            print '"' + str(u) + '" has left'
            del ulist[ulist.index(u)]
            refreshonlinelist()
            return [] #close the connection

def sendtoall(msg):
    for u in ulist:
        u.q.put(msg)

def ajax(write,user,message):
    sendtoall("<b>"+str(user)+":</b> "+message+"<br><script>window.scrollBy(0,100)</script>")

def online(write,user):
    write("<b>Who's Online:</b><br>")
    write("(" + str(len(ulist)) + " Online)<br>")
    for u in ulist:
        write(str(u)+"<br>\n")
    return []

def refreshonlinelist():
    sendtoall('<script>parent.frames["thelist"].location.reload()</script>')

import urllib

def function(environ, start_response):
    write = start_response('200 OK', [('Content-type', 'text/html')])
    patharray = environ['PATH_INFO'].split('/')
    if patharray==["",""]:
        index(write)
        return []
    if patharray[1]=="favicon.ico":
        return []
    command=patharray[1]
    user=patharray[2]
    if command=="top":
        top(write,user)
    elif command=="main":
        main(write,user)
    elif command=="ajax":
        ajax(write,user,urllib.unquote_plus(environ['QUERY_STRING']))
    elif command=="list":
        online(write,user)
    else:
        write("unknown command: "+str(command))
    return []

httpd = make_server('0.0.0.0', 9080, function)
print "Serving HTTP on port 9080..."
s=Server(httpd)
s.setName("Main Thread")
s.start()
s.join()#don't quit right away
